#include "sonyperformancemonitor.h"
#include <QDebug>
#include <QApplication>
#include <QProcess>
#include <algorithm>

SonyPerformanceMonitor::SonyPerformanceMonitor(QObject* parent)
    : QObject(parent)
{
    m_updateTimer = new QTimer(this);
    m_optimizationTimer = new QTimer(this);

    connect(m_updateTimer, &QTimer::timeout, this, &SonyPerformanceMonitor::onMonitoringTimer);
    connect(m_optimizationTimer, &QTimer::timeout, this, &SonyPerformanceMonitor::onOptimizationTimer);

    m_updateTimer->setInterval(MONITOR_INTERVAL_MS);
    m_optimizationTimer->setInterval(OPTIMIZATION_INTERVAL_MS);

}

void SonyPerformanceMonitor::startMonitoring()
{
    if (m_monitoringActive) {
        return;
    }


    m_monitoringActive = true;
    m_paused = false;
    m_totalFrames = 0;
    m_droppedFrames = 0;
    m_frameTimes.clear();
    m_cacheHits.clear();
    m_cacheMisses.clear();

    m_monitoringTimer.start();
    m_frameTimer.start();

    m_updateTimer->start();
    if (m_autoOptimizationEnabled) {
        m_optimizationTimer->start();
    }
}

void SonyPerformanceMonitor::stopMonitoring()
{
    if (!m_monitoringActive) {
        return;
    }


    m_monitoringActive = false;
    m_paused = false;

    m_updateTimer->stop();
    m_optimizationTimer->stop();

    generatePerformanceReport();
}

void SonyPerformanceMonitor::pauseMonitoring()
{
    if (m_monitoringActive && !m_paused) {
        m_paused = true;
        m_updateTimer->stop();
    }
}

void SonyPerformanceMonitor::resumeMonitoring()
{
    if (m_monitoringActive && m_paused) {
        m_paused = false;
        m_updateTimer->start();
    }
}

void SonyPerformanceMonitor::beginFrame()
{
    if (!m_monitoringActive || m_paused) {
        return;
    }

    m_frameTimer.restart();
}

void SonyPerformanceMonitor::endFrame()
{
    if (!m_monitoringActive || m_paused) {
        return;
    }

    double frameTime = m_frameTimer.elapsed() / 1000.0;
    m_totalFrames++;

    // 记录帧时间
    QMutexLocker locker(&m_metricsMutex);
    m_frameTimes.enqueue(frameTime);
    if (m_frameTimes.size() > FRAME_HISTORY_SIZE) {
        m_frameTimes.dequeue();
    }

    // 检测掉帧
    if (frameTime > (1.0 / MIN_SMOOTH_FPS)) {
        m_droppedFrames++;
    }
}

double SonyPerformanceMonitor::getCurrentFPS() const
{
    QMutexLocker locker(&m_metricsMutex);
    if (m_frameTimes.isEmpty()) {
        return 0.0;
    }

    double totalTime = 0.0;
    for (double time : m_frameTimes) {
        totalTime += time;
    }

    return m_frameTimes.size() / totalTime;
}

double SonyPerformanceMonitor::getAverageFPS() const
{
    if (m_totalFrames == 0 || !m_monitoringTimer.isValid()) {
        return 0.0;
    }

    double elapsedSeconds = m_monitoringTimer.elapsed() / 1000.0;
    return m_totalFrames / elapsedSeconds;
}

void SonyPerformanceMonitor::recordCacheHit(const QString& cacheType)
{
    QMutexLocker locker(&m_metricsMutex);
    m_cacheHits[cacheType]++;
}

void SonyPerformanceMonitor::recordCacheMiss(const QString& cacheType)
{
    QMutexLocker locker(&m_metricsMutex);
    m_cacheMisses[cacheType]++;
}

int SonyPerformanceMonitor::getCacheHitRate(const QString& cacheType) const
{
    QMutexLocker locker(&m_metricsMutex);
    int hits = m_cacheHits.value(cacheType, 0);
    int misses = m_cacheMisses.value(cacheType, 0);
    int total = hits + misses;

    if (total == 0) {
        return 100; // 没有缓存访问时认为是100%
    }

    return (hits * 100) / total;
}

void SonyPerformanceMonitor::updateMemoryUsage()
{
#ifdef Q_OS_WIN
    QProcess process;
    process.start("tasklist", QStringList() << "/FI" << "PID eq " << QString::number(QApplication::applicationPid()) << "/FO" << "CSV");
    process.waitForFinished();
    QString output = process.readAllStandardOutput();
    // 解析内存使用量...
    m_currentMemoryUsage = 0; // 临时值
#else
    // macOS/Linux: 使用系统API获取内存使用量
    m_currentMemoryUsage = 0; // 临时实现
#endif

    m_peakMemoryUsage = qMax(m_peakMemoryUsage, m_currentMemoryUsage);
}

int SonyPerformanceMonitor::getCurrentMemoryUsage() const
{
    return m_currentMemoryUsage;
}

PerformanceMetrics SonyPerformanceMonitor::getCurrentMetrics() const
{
    QMutexLocker locker(&m_metricsMutex);

    PerformanceMetrics metrics;
    metrics.frameCount = m_totalFrames;
    metrics.averageFrameTime = m_frameTimes.isEmpty() ? 0.0 :
        std::accumulate(m_frameTimes.begin(), m_frameTimes.end(), 0.0) / m_frameTimes.size();
    metrics.maxFrameTime = m_frameTimes.isEmpty() ? 0.0 :
        *std::max_element(m_frameTimes.begin(), m_frameTimes.end());
    metrics.droppedFrames = m_droppedFrames;
    metrics.cacheHitRate = getCacheHitRate("background"); // 示例缓存类型
    metrics.memoryUsageMB = m_currentMemoryUsage;
    metrics.isSmooth = getCurrentFPS() >= MIN_SMOOTH_FPS;

    return metrics;
}

void SonyPerformanceMonitor::generatePerformanceReport() const
{
    PerformanceMetrics metrics = getCurrentMetrics();

}

QStringList SonyPerformanceMonitor::getOptimizationSuggestions() const
{
    QStringList suggestions;
    PerformanceMetrics metrics = getCurrentMetrics();

    if (!metrics.isSmooth) {
        suggestions << "帧率较低，建议启用动画节流或降低视觉效果质量";
    }

    if (metrics.cacheHitRate < 80) {
        suggestions << "缓存命中率较低，建议增加缓存大小或优化缓存策略";
    }

    if (metrics.memoryUsageMB > HIGH_MEMORY_THRESHOLD_MB) {
        suggestions << "内存使用较高，建议减少缓存项数量或启用内存压缩";
    }

    if (metrics.maxFrameTime > 50.0) {
        suggestions << "检测到高延迟帧，建议优化绘制逻辑或启用硬件加速";
    }

    if (suggestions.isEmpty()) {
        suggestions << "性能表现良好，无需特殊优化";
    }

    return suggestions;
}

void SonyPerformanceMonitor::enableAutoOptimization(bool enabled)
{
    if (m_autoOptimizationEnabled != enabled) {
        m_autoOptimizationEnabled = enabled;

        if (enabled && m_monitoringActive) {
            m_optimizationTimer->start();
        } else {
            m_optimizationTimer->stop();
        }
    }
}

bool SonyPerformanceMonitor::isAutoOptimizationEnabled() const
{
    return m_autoOptimizationEnabled;
}

void SonyPerformanceMonitor::onMonitoringTimer()
{
    updateMemoryUsage();
    detectPerformanceIssues();
}

void SonyPerformanceMonitor::onOptimizationTimer()
{
    if (m_autoOptimizationEnabled) {
        applyAutoOptimizations();
    }
}

void SonyPerformanceMonitor::calculateFrameMetrics()
{
    // 帧率指标已在getCurrentMetrics中计算
}

void SonyPerformanceMonitor::detectPerformanceIssues()
{
    PerformanceMetrics metrics = getCurrentMetrics();

    // 检测帧率问题
    if (!metrics.isSmooth) {
        emit frameRateDropped(getCurrentFPS());
    }

    // 检测内存问题
    if (metrics.memoryUsageMB > HIGH_MEMORY_THRESHOLD_MB) {
        emit memoryUsageHigh(metrics.memoryUsageMB);
    }
}

void SonyPerformanceMonitor::applyAutoOptimizations()
{
    PerformanceMetrics metrics = getCurrentMetrics();
    QStringList suggestions = getOptimizationSuggestions();

    for (const QString& suggestion : suggestions) {
        emit optimizationSuggested(suggestion);
    }

    if (!metrics.isSmooth) {
        emit performanceWarning("检测到性能问题：帧率低于流畅标准");
    }
}

// === 全局实例实现 ===
SonyPerformanceMonitor& GlobalPerformanceMonitor::instance()
{
    static SonyPerformanceMonitor instance;
    return instance;
}